import { DataSource } from 'typeorm';
import { Tag } from '../../../entities/tag.entity';
import { Workspace } from '../../../entities/workspace.entity';

/**
 * 标签种子数据
 * 负责初始化常用标签
 */
export class TagSeed {
  constructor(private dataSource: DataSource) {}

  /**
   * 运行标签种子
   */
  async run(): Promise<void> {
    console.log('开始初始化标签数据...');

    const tagRepository = this.dataSource.getRepository(Tag);
    const workspaceRepository = this.dataSource.getRepository(Workspace);

    // 获取默认工作区
    const defaultWorkspace = await workspaceRepository.findOne({
      where: { name: '默认工作区' }
    });

    if (!defaultWorkspace) {
      console.log('未找到默认工作区，跳过标签初始化');
      return;
    }

    // 常用标签数据
    const commonTags = [
      { name: '紧急', color: '#FF0000', workspaceId: defaultWorkspace.id },
      { name: '重要', color: '#FFA500', workspaceId: defaultWorkspace.id },
      { name: '改进', color: '#4CAF50', workspaceId: defaultWorkspace.id },
      { name: '缺陷', color: '#F44336', workspaceId: defaultWorkspace.id },
      { name: '功能', color: '#2196F3', workspaceId: defaultWorkspace.id },
      { name: '文档', color: '#9C27B0', workspaceId: defaultWorkspace.id },
      { name: '设计', color: '#009688', workspaceId: defaultWorkspace.id },
      { name: '安全', color: '#FF5722', workspaceId: defaultWorkspace.id },
      { name: '优化', color: '#8BC34A', workspaceId: defaultWorkspace.id },
      { name: '接口', color: '#3F51B5', workspaceId: defaultWorkspace.id }
    ];

    // 创建常用标签
    for (const tagData of commonTags) {
      // 检查标签是否已存在
      const existingTag = await tagRepository.findOneBy({
        name: tagData.name,
        workspaceId: tagData.workspaceId
      });

      if (!existingTag) {
        const tag = tagRepository.create(tagData);
        await tagRepository.save(tag);
        console.log(`创建标签: ${tag.name}`);
      } else {
        console.log(`标签已存在: ${existingTag.name}`);
      }
    }

    console.log('标签数据初始化完成');
  }
} 